package project1.controller;
import com.google.gson.Gson;
import project1.model.Result;
import project1.model.User;
import project1.service.UserService;
import project1.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    Gson gson =new Gson();
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/","");

    }

    /**
     * 删除用户
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        userService.deleteUser(id);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        //System.out.println(requestURI);
        String action = requestURI.replace("/api/admin/user/","");
        if ("allUser".equals(action)){
            allUser(request,response);
        }
        if ("deleteUser".equals(action)){
            deleteUser(request,response);
        }
        if ("searchUser".equals(action)){
            searchUser(request,response);
        }
    }

    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<User> userList = userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(userList)));

    }


    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> allUser = userService.allUser();
        response.getWriter().println(gson.toJson(Result.ok(allUser)));
    }
}
